//
//  TLCommentManger.m
//  FunnyVideo
//
//  Created by 李鑫 on 15/9/19.
//  Copyright © 2015年 NewEggTech. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "TLCommentManger.h"

#import "TLVideoCell.h"
#import "TLCommentCell.h"
#import "TLAlertView.h"
#import "AVOSManger.h"




@interface TLCommentCellData : NSObject
@property (nonatomic,strong) NSMutableArray *names;
@property (nonatomic,strong) NSMutableArray *userHThumbs;
@property (nonatomic,strong) NSMutableArray *userCmts;
+ (TLCommentCellData *)createCmtDataWithAVOSResp:(NSArray *)avosResps;
@end

@implementation TLCommentCellData
+ (TLCommentCellData *)createCmtDataWithAVOSResp:(NSArray *)avosResps{
    TLCommentCellData *data = [[TLCommentCellData alloc] initWithAVOSResp:avosResps];
    return data;
}

- (id)initWithAVOSResp:(NSArray *)avosResps{
    self = [super init];
    self.names = [[NSMutableArray alloc] initWithCapacity:avosResps.count];
    self.userHThumbs = [[NSMutableArray alloc] initWithCapacity:avosResps.count];
    self.userCmts = [[NSMutableArray alloc] initWithCapacity:avosResps.count];
    if(self)
    {
        for(NSDictionary *resp in avosResps)
        {
            [self.names addObject:resp[@"username"]];
            [self.userHThumbs addObject:resp[@"userFace"]];
            [self.userCmts addObject:resp[@"comment"]];
        }
    }
    
    return self;
}
@end

@interface TLCommentManger ()

//out property
@property (nonatomic,strong) TLAlertView *container;
@property (nonatomic,weak)   TLVideoCell *videoCell;
@property (nonatomic,assign) CGAffineTransform cellTrans;
@property (nonatomic,weak)   UITableView *videoTable;
@property (nonatomic,strong) UITableView *commentTable;
@property (nonatomic,strong) NSString *v_id;
@property (nonatomic,assign) CGFloat scale;

@property (nonatomic,strong) NSDictionary *commentDic;
//inner property
@property (nonatomic,strong) TLCommentCell *currentCell;
@end
@implementation TLCommentManger
@synthesize container,isShowCmtView,isOn;

#pragma mark - Singleton
+ (TLCommentManger *)sharedManger{
    static dispatch_once_t onceToken;
    static TLCommentManger *manger;
    dispatch_once(&onceToken, ^{
        manger = [[TLCommentManger alloc] init];
    });
    
    return manger;
}
+ (UITableView *)sharedTable{
   return [[TLCommentManger sharedManger] commentTable];
}

+ (UIView *)sharedContainer{
    return [[TLCommentManger sharedManger] container];
}



- (void)reloadData{
    [self loadCommentDataWithVideoId:self.v_id startLoad:^{
        
    } loadCompletion:^(NSUInteger num, NSDictionary *dic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.commentTable reloadData];
        });
    }];
}

//View Create Methods
#pragma mark -- View Created Methods
- (UITableView *)createCommentTableViewSize:(CGSize)size{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height-InputBoxHeight) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = [UIColor lightTextColor];
    self.commentTable = tableView;
    
    tableView.estimatedRowHeight = 44.0f;
    tableView.rowHeight = UITableViewAutomaticDimension;
    
    return tableView;
}

- (TLAlertView *)createCommentViewHeightScale:(CGFloat)scale target:(id)target{
    CGSize size = CGSizeMake([TLDeviceManger deviceScreenSize].width, [TLDeviceManger deviceScreenSize].height * scale);
    
    TLAlertView *view = [[TLAlertView alloc] initWithFrame:CGRectMake(0, [TLDeviceManger deviceScreenSize].height, size.width, size.height) alertImage:[UIImage imageNamed:@""] refreshBlock:^(BOOL isTap) {
        if(isTap)
        {
            NSLog(@"Comment View Request To Reload the Comments");
        }
    }];
    
    view.backgroundColor = [UIColor whiteColor];
    
    return view;
}

+ (void)attachCommentTable{
    TLAlertView *container = [[TLCommentManger sharedManger] container] ;
    [container addSubview:[[TLCommentManger sharedManger] createCommentTableViewSize:container.frame.size]];
}

+ (void)toggleCommentByVideoId:(NSString *)v_id heightScale:(CGFloat)scale target:(UITableView *)target completion:(void (^)(BOOL))completionBlock{
    [TLCommentManger sharedManger].videoTable = target;
    
    if([TLCommentManger sharedManger].isShowCmtView)
    {
        [TLCommentManger dismissCommentView];
        completionBlock(NO);
    }
    else
    {
        /**
         *  start load comment data
         */
        [[[TLCommentManger sharedManger] container] showAlert:TLAlertTypeNoneData];
        
        [TLCommentManger requestShowCommentByVideoId:v_id heightScale:scale target:target completion:^(BOOL isFinished) {
            //copy Video Id
            [[TLCommentManger sharedManger] setV_id:v_id];
            [[TLCommentManger sharedManger]  loadCommentDataWithVideoId:v_id startLoad:^{
            
            }loadCompletion:^(NSUInteger code, NSDictionary *cmtDic) {
                if(![AVOSErrorManger errorExsit:code])
                dispatch_async(dispatch_get_main_queue(), ^{
                [TLCommentManger attachCommentTable];
                [[[TLCommentManger sharedManger] commentTable] reloadData];
                });
                else
                [[[TLCommentManger sharedManger] container] showAlert];
                completionBlock(YES);
            }];
        }];
    }
}

+ (void)requestShowCommentByVideoId:(NSString *)v_id heightScale:(CGFloat)scale target:(UITableView *)target completion:(void (^)(BOOL))completionBlock{
    
    TLAlertView *cmtView = [[TLCommentManger sharedManger] createCommentViewHeightScale:scale target:target];
    
    
    cmtView.layer.contents = (id)[UIImage imageNamed:@"NoneCmt"].CGImage;
    [TLCommentManger sharedManger].container = cmtView;
    
    [[[UIApplication sharedApplication] keyWindow].subviews[0] addSubview:cmtView];
    
    [UIView animateWithDuration:0.8 delay:0 usingSpringWithDamping:2.3 initialSpringVelocity:1.3 options:UIViewAnimationOptionTransitionCurlUp animations:^{
        CGRect o_rect = [cmtView frame];
        
        cmtView.frame = CGRectMake(0, o_rect.origin.y * (1-scale), o_rect.size.width, o_rect.size.height);
        
        [[TLCommentManger sharedManger] setIsShowCmtView:YES];
        
    } completion:^(BOOL finished) {
        completionBlock(finished);
    }];
}

//dismiss comment view
+ (BOOL)dismissCommentView{
    if(![TLCommentManger sharedManger].isShowCmtView)
        return NO;
    else
    {   TLAlertView *cmtView = [[TLCommentManger sharedManger] container];
        //dismiss Comment View
        [UIView animateWithDuration:1.3 delay:0 usingSpringWithDamping:2.3 initialSpringVelocity:1.3 options:UIViewAnimationOptionTransitionCurlDown animations:^{
            //CommentView animation
            CGRect o_rect = [cmtView frame];
            
            cmtView.frame = CGRectMake(0, [TLDeviceManger deviceScreenSize].height, o_rect.size.width, o_rect.size.height);
            [[TLCommentManger sharedManger] setIsShowCmtView:NO];
            //Video Cell Animation
            [[TLCommentManger sharedManger] videoCell].transform =CGAffineTransformIdentity;
            [[[TLCommentManger sharedManger] videoTable] addSubview:[[TLCommentManger sharedManger] videoCell]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[[TLCommentManger sharedManger] videoTable] reloadData];
            });
        } completion:^(BOOL finished) {
            [cmtView removeFromSuperview];
        }];
        
        return YES;
    }
}

+ (void)scaleVideoView:(TLVideoCell *)videoView{
    //transform assign
    [TLCommentManger sharedManger].cellTrans = videoView.transform;
    
    NSLog(@"%@",NSStringFromCGAffineTransform([TLCommentManger sharedManger].cellTrans));
    //pointer for remove
    [TLCommentManger sharedManger].videoCell = videoView;
    //Origin
    CGPoint navOrigin = CGPointMake([[UIApplication sharedApplication] statusBarFrame].origin.x, [[UIApplication sharedApplication] statusBarFrame].size.height);
    //Screen Width
    CGFloat screenWidth = [[UIApplication sharedApplication] statusBarFrame].size.width;
    
    float scaleFactor = screenWidth/videoView.cellBackgroundView.frame.size.width;
    
   // CGRect newVideoViewFrame  = CGRectMake(navOrigin.x, navOrigin.y, videoView.frame.size.width*scaleFactor, videoView.frame.size.height*scaleFactor);
    //Convert Video Frame to Window Frame
    UIView *windowView = [[UIApplication sharedApplication] keyWindow].subviews[0];
    
    CGRect transFrame = [windowView convertRect:videoView.frame fromView:[[TLCommentManger sharedManger] videoTable]];
    CGRect targetFrame = CGRectMake(0, navOrigin.y, transFrame.size.width, transFrame.size.height);
    
    [videoView setFrame:targetFrame];
    
    [windowView addSubview:videoView];
    
    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:3.3 initialSpringVelocity:1.3 options:UIViewAnimationOptionTransitionCurlUp animations:^{
        //CGPoint covertPoint = [videoView convertPoint:videoView.frame.origin toView:windowView];
        
        //NSLog(@"scale factor %f",scaleFactor);
        
        videoView.transform = CGAffineTransformMakeScale(scaleFactor, scaleFactor);
        
        //videoView.transform = CGAffineTransformTranslate(videoView.transform, 0, navOrigin.y);
        
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - UITableView Delegate
- (CGFloat)tableView:(nonnull UITableView *)tableView estimatedHeightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    return 180;
}


- (CGFloat)tableView:(nonnull UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    self.currentCell.textLabel.text =  [[self.commentDic objectForKey:@"results"] objectAtIndex:indexPath.row][@"comment"];
    CGSize fitSize = [self.currentCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    CGFloat tWidth = self.currentCell.userComment.frame.size.width;
    
    CGSize tSize = [self.currentCell.userComment sizeThatFits:TFIL_MAX(tWidth)];
    
    NSLog(@"Fit Size for current cell %@",NSStringFromCGSize(fitSize));
    
    return fitSize.height + 1 + tSize.height;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [(NSArray *)self.commentDic[@"results"] count];
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //dequeue reuse
    TLCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CMTCell"];
    
    if(!cell)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TLCommentCell" owner:self options:nil];
        if ([nib count]>0)
        {
            cell = [nib objectAtIndex:0];
        }
    }
    NSString *username = [[self.commentDic objectForKey:@"results"] objectAtIndex:indexPath.row][@"postUser"];
    

    cell.userName.text = ![username isEqual:[NSNull null]]? username : @"未知";
    cell.cmtObjId = [[self.commentDic objectForKey:@"results"] objectAtIndex:indexPath.row][@"objectId"];
    
    NSNumber *supportCount = [[self.commentDic objectForKey:@"results"] objectAtIndex:indexPath.row][@"supportCount"];
    cell.supportLabel.text = ![supportCount isEqual:[NSNull null]]? [supportCount stringValue] : @"0";
    [cell fetchImgWithName:cell.userName.text];
    
    NSString *comment = [[self.commentDic objectForKey:@"results"] objectAtIndex:indexPath.row][@"comment"];
    
    cell.userComment.text = ![comment isEqual:[NSNull null]] ? comment:@"未知";
    
    self.currentCell = cell;
    
    return cell;
}

#pragma mark - Property Set
- (void)setIsOn:(TLCommentViewStatus)isOn_{
    isOn = isOn_;
}

- (void)setIsShowCmtView:(BOOL)isShowCmtView_{
    isShowCmtView = isShowCmtView_;
    [self setIsOn:(isShowCmtView_ ? TLCommentViewStatusOn : TLCommentViewStatusOff)];
}

#pragma mark - Comment Data Methods
- (void)loadCommentDataWithVideoId:(NSString *)v_id startLoad:(void(^)())startLoadBlock loadCompletion:(void(^)(NSUInteger,NSDictionary*))cplBlock{
    //start load
    startLoadBlock();
    
    [[AVOSManger sharedManger] getCommentWithVideoId:v_id completion:^(NSUInteger httpcode, NSDictionary *cmtDic) {
        
        [[TLCommentManger sharedManger] setCommentDic:cmtDic];
        
        cplBlock([self errorCodeForDic:cmtDic httpCode:httpcode],cmtDic);
    }];
}

- (NSUInteger)errorCodeForDic:(NSDictionary *)dic httpCode:(NSUInteger)httpcode
{
    if(httpcode == 200)
    {
    if(![(NSArray *)dic[@"results"] count])
        return AVOSErrorCodeNoneData;
    else
        return AVOSErrorCodeNone;
    }
    
    return AVOSErrorCodeNetBlock;
}
@end
